package server;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandler;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SimpleContext {

    private String docBase;
    private String path;
    private Map<String,HttpServlet> servletMap;

    public String getDocBase() {
        return docBase;
    }

    public void setDocBase(String docBase) {
        this.docBase = docBase;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public Map<String, HttpServlet> getServletMap() {
        return servletMap;
    }

    public void setServletMap(Map<String, HttpServlet> servletMap) {
        this.servletMap = servletMap;
    }

    public void initServlet(String appBase) {

        servletMap = new HashMap<>();

        URLClassLoader loader = null;
        String contextName = path.substring(1);
        try {
            URL[] urls = new URL[1];
            URLStreamHandler urlStreamHandler = null;
            File classpath = new File(appBase + File.separator + contextName);
            String repository = (new URL("file", null, classpath.getCanonicalPath() + File.separator)).toString();
            urls[0] = new URL(repository);
            loader = new URLClassLoader(urls);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        //
        try {
            String webXml = appBase + File.separator + contextName + File.separator + "web.xml";
            InputStream resourceAsStream = new FileInputStream(webXml);
            SAXReader saxReader = new SAXReader();

            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();


                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                Class servletClazz = loader.loadClass(servletClass);
                HttpServlet httpServlet = (HttpServlet) servletClazz.newInstance();
                servletMap.put(urlPattern, httpServlet);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void invoke(Request request, Response response) {
        String url = request.getUrl();
        int secondSlashIndex = url.indexOf("/", 1);
        String urlWithoutContext = url.substring(secondSlashIndex);

        try {
            // 静态资源处理
            if(servletMap.get(urlWithoutContext) == null) {
                response.outputHtml(urlWithoutContext);
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(urlWithoutContext);
                httpServlet.service(request,response);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
